#!/usr/bin/env python
# --*-- coding:utf-8 --*--
# author:g-y-b time:2020/5/24
import csv
import random
import math
import operator


def loadDataset(filename, split, trainingSet=[], testSet=[]):
    with open(filename, 'r', encoding='utf-8') as csvfile:
        lines = csv.reader(csvfile)
        dataset = list(lines)
        for x in range(1, len(dataset)):
            print(x, ':')
            dataset[x].pop(0)
            for y in range(4):
                dataset[x][y] = float(dataset[x][y])
                print(dataset[x])
            if random.random() < split:
                trainingSet.append(dataset[x])
            else:
                testSet.append(dataset[x])


def euclideanDistance(instance1, instance2, length):    # 计算欧氏距离
    distance = 0
    for x in range(length):
        distance += pow((instance1[x] - instance2[x]), 2)
    return math.sqrt(distance)


def getNeighbors(traingSet, testInstance, k):     # 返回最近的k个邻居
    distances = []
    length = len(testInstance) - 1
    for x in range(len(traingSet)):
        dist = euclideanDistance(testInstance, traingSet[x], length)
        distances.append((traingSet[x], dist))
    distances.sort(key=operator.itemgetter(1))
    neighbors = []
    for x in range(k):
        neighbors.append(distances[x][0])
    return neighbors


def getResponse(neighbors):     # 进行投票
    classVotes = {}
    for x in range(len(neighbors)):
        response = neighbors[x][-1]
        if response in classVotes:
            classVotes[response] += 1
        else:
            classVotes[response] = 1
    sortedVotes = sorted(classVotes.items(), key=operator.itemgetter(1), reverse=True)  # 按降序排列
    return sortedVotes[0][0]


def getAccuracy(testSet, predictions):
    correct = 0
    for x in range(len(testSet)):
        if testSet[x][-1] == predictions[x]:
            correct += 1
    return (correct/float(len(testSet))) * 100.0


def main():
    trainingSet = []
    testSet = []
    split = 0.67
    loadDataset('iris.csv', split, trainingSet, testSet)

    predictions = []
    k = 3
    print(trainingSet)
    for x in range(len(testSet)):
        neighbors = getNeighbors(trainingSet, testSet[x], k)
        # print(neighbors)
        result = getResponse(neighbors)
        predictions.append(result)
        # print('>predicted='+repr(result)+',actual='+repr(testSet[x][-1]))
    accuracy = getAccuracy(testSet, predictions)
    print('Accuracy:'+repr(accuracy)+'%')


main()
